package bupt.com.test.widget;

import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.support.annotation.NonNull;
import android.util.TypedValue;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by Jc on 2015/12/18.
 * bitmap工具
 */
public class BitmapUtil {

    /**
     * 图片的缩放方法
     *
     * @param source    ：源图片资源
     * @param newWidth  ：缩放后宽度
     * @param newHeight ：缩放后高度
     * @return
     */
    public static Bitmap zoomImage(Bitmap source, double newWidth,
                                   double newHeight) {
        // 获取这个图片的宽和高
        float width = source.getWidth();
        float height = source.getHeight();

        Bitmap source2 = null;

        // 如果图片被旋转了90度，给正过来
        if(width > height) {
            source2 = rotateBitmap(source, 90);
        }

        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();
        // 缩放图片
        Bitmap newBm;
        if(source2 == null) {
            float scaleX = ((float) newWidth) / width;
            float scaleY = ((float) newHeight) / height;
            matrix.postScale(scaleX, scaleY);
            newBm =Bitmap.createBitmap(source, 0, 0, source.getWidth(),
                    source.getHeight(), matrix, true);
            // source高宽与newWidth和newHeight相同时会直接返回source，需判断下是否要回收
            if(scaleX != 1.0f || scaleY != 1.0f) {
                source.recycle();
            }
        } else {
            float scaleX = ((float) newWidth) / height;
            float scaleY = ((float) newHeight) / width;
            matrix.postScale(scaleX, scaleY);
            newBm =Bitmap.createBitmap(source2, 0, 0, source2.getWidth(),
                    source2.getHeight(), matrix, true);
            if(scaleX != 1.0f || scaleY != 1.0f) {
                source2.recycle();
            }
        }
        return newBm;
    }

    /**
     * 计算inSampleSize，确保小于4096
     *
     * @param options 用于获取图片尺寸
     * @return inSampleSize
     */
    public static int calculateInSampleSize(BitmapFactory.Options options) {
        int width = options.outWidth;
        int height = options.outHeight;
        int inSampleSize = 0;
        if (width > 4096 || height > 4096) {
            if (width >= height) {
                inSampleSize = width / 4096;
            } else {
                inSampleSize = height / 4096;
            }
        }
        if (inSampleSize <= 1) {
            inSampleSize += 1;
        }
        return inSampleSize;
    }

    /**
     * 保存图片到SD卡
     */
    public static boolean saveBitmapToFile(Bitmap bitmap, String dir, String fileName) {
        boolean success = false;
        File file = null;
        BufferedOutputStream fos = null;
        file = new File(dir);
        try {
            if (!file.exists()) {
                file.mkdirs();
            }
            File fileSave = new File(dir + "/" + fileName);
            fos = new BufferedOutputStream(new FileOutputStream(fileSave));
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            success = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) fos.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
        return success;
    }

    /**
     * 获取SD卡中保存的图片
     */
    public static Bitmap getBitmapFromFile(@NonNull String filePath) {
        Bitmap bitmap = null;
        File file = new File(filePath);
        if (file.exists()) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            options.inSampleSize = calculateInSampleSize(options);
            options.inJustDecodeBounds = false;
            bitmap = BitmapFactory.decodeFile(filePath, options);
        }
        return bitmap;
    }

    /**
     * 获取网络图片
     *
     * @param url
     * @return
     */
    public static Bitmap getHttpBitmap(String url) {
        Bitmap bitmap = null;
        try {
            URL pictureUrl = new URL(url);
            InputStream in = pictureUrl.openStream();
            bitmap = BitmapFactory.decodeStream(in);
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }


    /**
     * 获取asset中的图片
     */
    public static Bitmap getImageFromAssetFile(String fileName, Context context) {
        Bitmap bitmap = null;
        AssetManager am = context.getResources().getAssets();
        try {
            InputStream is = am.open(fileName);
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 获取图片文件的信息，是否旋转了90度，如果是则反转
     * @param bitmap 需要旋转的图片
     * @param path   图片的路径
     */
    public static Bitmap reviewPicRotate(Bitmap bitmap, String path) {
        int degree = getPicRotate(path);
        if (degree != 0) {
            Matrix m = new Matrix();
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            m.setRotate(degree); // 旋转angle度
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, m, true);// 从新生成图片
        }
        return bitmap;
    }

    /**
     * 读取图片文件旋转的角度
     *
     * @param path 图片绝对路径
     * @return 图片旋转的角度
     */
    public static int getPicRotate(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 旋转图片，使图片保持正确的方向。
     * @param bitmap 原始图片
     * @param degrees 原始图片的角度
     * @return Bitmap 旋转后的图片
     */
    public static Bitmap rotateBitmap(Bitmap bitmap, int degrees) {
        if (degrees == 0 || null == bitmap) {
            return bitmap;
        }
        Matrix matrix = new Matrix();
        matrix.setRotate(degrees);
        Bitmap bmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        bitmap.recycle();
        return bmp;
    }

    /**
     * 从raw获取bitmap
     * @param resources
     * @param id
     * @return
     */
    public static Bitmap decodeRawResource(Resources resources, int id) {
        TypedValue value = new TypedValue();
        resources.openRawResource(id, value);
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inTargetDensity = value.density;
        return BitmapFactory.decodeResource(resources, id, opts);
    }
}
